package com.google.antranking.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.antranking.R;



public class CircleOverlay extends Overlay {

	//private Geocoder geoCoder = null;

	private GeoPoint geoPoint;
	
	private MapView mapView;

	private Context context;
	
	//private float circleRadius;
	
	private double radiusRadian; 

	public CircleOverlay(Context context, GeoPoint geoPoint,  double radiusRadian) {
		super();
		this.geoPoint = geoPoint;
		this.context = context;
		this.radiusRadian = radiusRadian;
		//this.geoCoder = new Geocoder(context);
	}

	@Override
	public boolean onTap(GeoPoint geoPoint, MapView mapView) {
		return super.onTap(geoPoint, mapView);
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		this.mapView = mapView;
		if (shadow) {

			// Convert geoPoint in pixelPoint
			final Point pt = new Point();
			mapView.getProjection().toPixels(geoPoint, pt);
			
			float circleRadius = calculateRadius();
			
			// Paint circle 
			final Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
			circlePaint.setColor(0x30000000);
			circlePaint.setStyle(Style.FILL_AND_STROKE);
			canvas.drawCircle((float) pt.x, (float) pt.y, circleRadius, circlePaint);
			circlePaint.setColor(0x99000000);
			circlePaint.setStyle(Style.STROKE);
			canvas.drawCircle((float) pt.x, (float) pt.y, circleRadius,
					circlePaint);
			
			// Paint icon
			final Bitmap markerBitmap = BitmapFactory.decodeResource(
					context.getResources(), R.drawable.ic_pin);
			canvas.drawBitmap(markerBitmap, pt.x,
					pt.y - markerBitmap.getHeight(), null);

			super.draw(canvas, mapView, shadow);
		}
	}
	
	public float calculateRadius(){
		
		final Point pt = new Point();
		mapView.getProjection().toPixels(geoPoint, pt);
		
		final GeoPoint geoPoint2 = new GeoPoint(
				(int)(geoPoint.getLatitudeE6()+(this.radiusRadian*1E6)),
				geoPoint.getLongitudeE6());
		
		final Point pt2 = new Point();
		mapView.getProjection().toPixels(geoPoint2, pt2);
		
		return
				(float) Math.sqrt(
							Math.pow((pt.x - pt2.x),2)
							+
							Math.pow((pt.y - pt2.y),2)
				);
	}
	
	
	public String getGeocode(){
		return "Unknown";
	}
	
}
